import 'dart:math';
import 'package:ball_lion/module/record/league_channel_logic.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/base/wqs_indicator.dart';
import 'package:ball_lion/utils/date_time_utils.dart';

class LeagueChannelPage extends StatelessWidget {
  LeagueChannelPage({super.key});
  final int tag = Random().nextInt(100000);
  late final LeagueChannelLogic logic;
  @override
  Widget build(BuildContext context) {
    return GetBuilder<LeagueChannelLogic>(
        initState: (state) =>
            logic = Get.put(LeagueChannelLogic(), tag: "$tag"),
        tag: "$tag",
        builder: (logic) {
          return Scaffold(
              extendBodyBehindAppBar: true,
              appBar: Styles.appBar(
                  showLeading: true,
                  systemUiOverlayStyle: const SystemUiOverlayStyle(
                      statusBarIconBrightness: Brightness.light),
                  backgroundColor: Colours.transparent,
                  leadingColor: Colours.white),
              body: logic.isLoading
                  ? Container()
                  : Stack(
                      children: [
                        Image.asset(
                            height: 320,
                            width: Get.width,
                            alignment: Alignment.bottomCenter,
                            fit: BoxFit.cover,
                            Utils.getImgPath("channel_background.png")),
                        SafeArea(
                          child: Column(
                            children: [
                              Container(height: 10),
                              channelHead(),
                              if (logic.entity?.startTime != null)
                                channelProgress().paddingOnly(top: 20),
                              Container(height: 22),
                              Container(
                                  width: Get.width,
                                  decoration: const BoxDecoration(
                                      color: Colours.white,
                                      borderRadius: BorderRadius.vertical(
                                          top: Radius.circular(10))),
                                  child: Row(
                                    children: [
                                      Expanded(
                                        child: SizedBox(
                                          height: 40,
                                          child: Styles.tabbar(
                                            controller: logic.controller,
                                            tabs: logic.typeList
                                                .map((e) => QsText(e))
                                                .toList(),
                                            onTap: (index) =>
                                                logic.typeIndex = index,
                                            indicator: QsIndicator(
                                                borderSide: BorderSide(
                                                    width: 3,
                                                    color: Colours.main),
                                                indicatorBottom: 2,
                                                indicatorWidth: 16),
                                          ),
                                        ),
                                      ),
                                      GestureDetector(
                                        onTap: () {
                                          Utils.onEvent("sjpd_lx",
                                              params: {"sjpd_lx": 0});
                                          logic.showDatePicker();
                                        },
                                        child: Container(
                                          key: ValueKey(logic.channelId),
                                          width: 52,
                                          height: 20,
                                          alignment: Alignment.center,
                                          margin:
                                              const EdgeInsets.only(right: 8),
                                          decoration: BoxDecoration(
                                              border: Border.all(
                                                  color: Colours.grey99,
                                                  width: 0.5),
                                              borderRadius:
                                                  BorderRadius.circular(15)),
                                          child: Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.center,
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.center,
                                              children: [
                                                QsText(
                                                    logic.season.length > 4
                                                        ? ("${logic.season.substring(2, 4)}/${logic.season.substring(7, 9)}")
                                                        : logic.season,
                                                    needCenter: true,
                                                    fontSize: 12),
                                                const SizedBox(width: 2),
                                                Padding(
                                                  padding:
                                                      const EdgeInsets.only(
                                                          top: 1),
                                                  child: Image.asset(
                                                      width: 6,
                                                      Utils.getImgPath(
                                                          'down_arrow.png')),
                                                )
                                              ]),
                                        ),
                                      )
                                    ],
                                  )),
                              Expanded(
                                  child: Container(
                                color: Colours.white,
                                child: TabBarView(
                                    controller: logic.controller,
                                    children: logic.page),
                              ))
                            ],
                          ),
                        ),
                      ],
                    ));
        });
  }

  Widget channelHead() {
    return Row(children: [
      CachedNetworkImage(
          width: 54,
          height: 54,
          fit: BoxFit.fitWidth,
          imageUrl: logic.entity?.channelLogo ?? "",
          placeholder: (context, url) => Styles.placeholderIcon(),
          errorWidget: (context, url, error) => Image.asset(
                fit: BoxFit.fitHeight,
                Utils.getImgPath('zq_placeholder.png'),
                height: 54,
                width: 54,
              )),
      const SizedBox(width: 12),
      Expanded(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            QsText(logic.entity?.nameChs ?? '',
                fontSize: 20, color: Colours.white),
            QsText(logic.entity?.nameEn ?? "",
                color: Colours.white.withOpacity(0.8))
          ],
        ),
      ),
      Container(width: 10),
      focusWidget()
    ]).paddingSymmetric(horizontal: 16);
  }

  Widget channelProgress() {
    return GetBuilder<LeagueChannelLogic>(
        tag: tag.toString(),
        builder: (logic) {
          return Column(
            children: [
              DefaultTextStyle(
                style: TextStyle(fontSize: 12, color: Colors.white),
                child: Container(
                  height: 16,
                  alignment: Alignment.center,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      QsText(
                          DateTime.tryParse(logic.entity?.startTime ?? "")
                                  ?.formatedString("yyyy/MM/dd") ??
                              "",
                          color: Colors.white.withOpacity(0.8)),
                      QsText(
                          DateTime.tryParse(logic.entity?.endTime ?? "")
                                  ?.formatedString("yyyy/MM/dd") ??
                              "",
                          color: Colors.white.withOpacity(0.8))
                    ],
                  ).paddingSymmetric(horizontal: 16),
                ),
              ),
              Container(
                  width: Get.width,
                  height: 16,
                  padding: EdgeInsets.all(2),
                  alignment: Alignment.centerLeft,
                  margin: EdgeInsets.only(left: 16, right: 16),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8),
                      color: Colours.black2C2E37),
                  child: LayoutBuilder(builder:
                      (BuildContext context, BoxConstraints constraints) {
                    return Stack(
                      clipBehavior: Clip.none,
                      children: [
                        Container(
                            clipBehavior: Clip.antiAlias,
                            width: constraints.maxWidth *
                                ((logic.entity?.progress ?? 0) / 100),
                            height: 16,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Image.asset(
                                height: 14,
                                fit: BoxFit.fitHeight,
                                Utils.getImgPath("channel_progress.png"))),
                        Positioned(
                            left: (logic.entity?.progress ?? 0) < 10 ? 0 : null,
                            right:
                                (logic.entity?.progress ?? 0) < 10 ? null : 0,
                            top: 0,
                            bottom: 0,
                            child: QsText(logic.progress,
                                    needCenter: true,
                                    fontSize: 10,
                                    color: Colors.white)
                                .paddingSymmetric(horizontal: 6))
                      ],
                    );
                  })),
            ],
          );
        });
  }

  Widget focusWidget() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16),
      child: GestureDetector(
        onTap: logic.onFocus,
        child: Container(
          height: 24,
          width: 56,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
              border: Border.all(
                  color: logic.entity?.isFocus == 0
                      ? Colours.white
                      : Colours.white.withOpacity(0.6),
                  width: 0.5)),
          child: QsText(
            logic.entity?.isFocus == 0 ? '关注' : '已关注',
            needCenter: true,
            color: logic.entity?.isFocus == 0
                ? Colours.white
                : Colours.white.withOpacity(0.6),
            fontSize: 13,
          ),
        ),
      ),
    );
  }
}
